package com.gyh.stlserver.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gyh.stlserver.entity.Member;
import com.gyh.stlserver.mapper.MemberMapper;
import com.gyh.stlserver.service.MemberService;
import com.gyh.stlserver.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Override
    public PageInfo<Member> getAllMember(Integer pageNum, Integer pageSize, Member member) {
        PageHelper.startPage(pageNum,pageSize);
        List<Member> members = memberMapper.select(member);
        return new PageInfo<>(members);
    }

    @Override
    public int addMember(Member member) {
        String pwd = PasswordUtil.md5encryption(member.getPassword());
        member.setPassword(pwd);
        member.setCreateTime(new Date());
        return memberMapper.insert(member);
    }

    @Override
    public Member checkName(String name) {
        return memberMapper.selectMemberByName(name);
    }

    @Override
    public Member checkPhone(String phone) {
        return memberMapper.selectMemberByPhone(phone);
    }

    @Override
    public Member getMemberById(Integer id) {
        return memberMapper.selectMemberById(id);
    }

    @Override
    public int editMember(Member member) {
        /*加密*/
        if (StrUtil.isNotBlank(member.getPassword())){
           member.setPassword(PasswordUtil.md5encryption(member.getPassword()));
        }
        return memberMapper.update(member);
    }

    @Override
    public int remove(Integer id) {
        return memberMapper.deleteMemberById(id);
    }

    @Override
    public int removeByIds(Integer[] ids) {
        return memberMapper.deleteMemberByIds(ids);
    }

    @Override
    public List<Member> getAll() {
        return memberMapper.select(null);
    }

    @Override
    public int payBalance(Double balance, Integer memberId) {
        Member member = memberMapper.selectMemberById(memberId);
        member.setBalance(member.getBalance().add(new BigDecimal(balance)));
        return memberMapper.update(member);
    }

    @Override
    public int consumeBalance(Double balance, Integer memberId) {
        Member member = memberMapper.selectMemberById(memberId);
        BigDecimal balance2 = member.getBalance().subtract(new BigDecimal(balance));
        if (balance2.compareTo(new BigDecimal(0)) < 0){
            throw new RuntimeException("余额不足");
        }
        member.setBalance(balance2);
        return memberMapper.update(member);
    }
}
